import axios from 'axios'
import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { getparam } from '@/utils/util'
import { ACCESS_TOKEN } from '@/store/mutation-types'

let baseUrl = window.PROJECT_CONFIG.VUE_APP_API_BASE_URL

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: baseUrl,
  timeout: 6000 * 10 * 5 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = (error) => {
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    const token = storage.get(ACCESS_TOKEN)
    if (+error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message
      })
    }
    if (+error.response.status === 404) {
      notification.error({
        message: '错误',
        description: '请求目标地址不存在!'
      })
      return {}
    }
    if (+error.response.status === 401 || +error.response.data.code === 401) {
      notification.error({
        message: 'Unauthorized',
        description: 'Authorization verification failed'
      })
      store.dispatch('Logout').then(() => {
        setTimeout(() => {
          window.location.reload()
        }, 1500)
      })
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  const token = storage.get(ACCESS_TOKEN)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  let headers = {
    'Content-Type': 'application/json'
  }
  if (token) {
    headers[ACCESS_TOKEN] = `Bearer ${token}`
  }
  config.headers = headers
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  const res = response.data
  if (+res.code === 200) {
    return Promise.resolve(res.result)
  } else if (+res.code === 500) {
    notification.error({
      message: '错误',
      description: '系统异常!'
    })
    return Promise.reject(false)
  } else if (+res.code === 401) {
    // notification.error({
    //   message: 'Unauthorized',
    //   description: 'Authorization verification failed'
    // })
    store.dispatch('Logout').then(() => {
      setTimeout(() => {
        window.location.reload()
      }, 1500)
    })
    return Promise.reject(false)
  } else {
    notification.error({
      message: '错误',
      description: response.data.message
    })
    return Promise.reject(false)
  }
}, errorHandler)

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, request)
  }
}

function downloadFile(data, type = 1) {
  const { url, params } = data
  if(type === 1){
    window.open(baseUrl + url + getparam(params || {}), '_blank')
    return
  }
  const token = storage.get(ACCESS_TOKEN)
  // TODO 暂时采用此方法处理、后期如有其他问题需要以下方axios异步方式处理
  return new Promise((resolve, reject) => {
    axios({
      url: window.PROJECT_CONFIG.VUE_APP_API_BASE_URL + url,
      method: 'POST',
      data: JSON.parse(JSON.stringify(params)),
      responseType: 'blob',
      headers: {
        [ACCESS_TOKEN]: `Bearer ${token}`
      }
    }).then((res) => {
      const blob = res.data
      const a = document.createElement('a')
      const headers = res.headers
      let fileName = headers['content-disposition']
      fileName = fileName.split(';')[1].split('=')[1]
      a.download = window.decodeURIComponent(fileName).replace(/\+/g, ' ')

      a.href = window.URL.createObjectURL(blob)
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      resolve(true)
    }).catch(_ => {
      reject(false)
    })
  })
}

export default request

export {
  installer as VueAxios,
  request as axios,
  downloadFile
}
